class Grid {
  $grid;
  row;
  col;
  areas;
  areasCopy;
  // 刷新
  refreshLayout;
  areasHides = new Set();
  constructor(refreshLayout) {
    this.refreshLayout = refreshLayout
  }

  /**
   * 创建布局列表数组值
   */
  createGridArea (defaultAreas) {
    const { row, col } = this;
    const areas = [];
    for (let i = 1; i <= row * col; i++) {
      const index = i < 10 ? `0${i}` : i
      areas.push(`grid-area-${ index }`)
    }

    this.areas = areas
    this.areasCopy = defaultAreas || [...areas]
    return areas;
  }

  /**
   * 创建布局盒子
   *
   * @param row
   * @param col
   * @param gap
   * @returns {*}
   */
  createGridBox ([row, col] = [1, 1], gap = [6, 6]) {
    const [rowGap, columnGap] = gap;
    const rowStyle = `repeat(${row}, 1fr)`;
    const colStyle = `repeat(${col}, 1fr)`;
    const className = `sullivan-grid sullivan-grid-${row}x${col}`;

    this.$grid = $(`<div class="${className}" style="display: grid;" ></div>`);
    this.row = row;
    this.col = col;

    this.$grid.css({
      "grid-template-rows": rowStyle,
      "grid-template-columns": colStyle,
      "grid-row-gap": rowGap,
      "grid-column-gap": columnGap,
    });

    return this.$grid
  }

  /**
   * 创建网格布局内容
   */
  createGridLayout(isUpdate) {
    const areas = [...new Set(this.areasCopy)]
    const createDirection = (direction) => (
      `<div class="sullivan-grid-item-direction sullivan-grid-item-${direction}"></div>`
    );
    this.$grid.empty();
    areas.forEach((area, i) => {
      const $gridItem = $(
        `<div class="sullivan-grid-item ${area}" data-index="${i + 1}" data-area="${area}" style="grid-area:
                        ${area}"><div class="sullivan-grid-item-content"></div></div>`
      );
      $gridItem.find('.sullivan-grid-item-content').append(['top', 'right', 'bottom', 'left'].map(createDirection))
      this.$grid.append($gridItem);
    })

    if (isUpdate && typeof this.refreshLayout === 'function') this.refreshLayout(areas)
    return this.$grid;
  }

  /**
   * 更新
   *
   * @param index
   * @param area
   */
  update (index, area) {
    this.areasCopy[index] = area;
    if (this.areasCopy.includes(area)) {
      this.areasHides.add(area)
    } else {
      this.areasHides.delete(area)
    }
    this.setGridAreaCss()
  }

  createGridAreaCss = (areas, col) => {
    let tempAreas = ``

    areas.forEach((item, index) => {
      if (index % col || index === 0) {
        tempAreas += `${item} `
      } else {
        tempAreas += `" "${item} `
      }
    })

    return `"${tempAreas}"`
  }

  /**
   * 设置布局 css
   */
  setGridAreaCss () {
    let tempAreas = this.createGridAreaCss(this.areasCopy, this.col)
    this.$grid.css({
      "grid-template-areas": tempAreas
    });

    console.log('setGridArea: => ', this.areas, this.areasCopy, tempAreas)
  }
}